#include "setwig.h"
#include "ui_setwig.h"

//设置界面
SetWig::SetWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SetWig)
{
    ui->setupUi(this);

    udpSocket = new QUdpSocket;
    //    udpSocket->bind(1024,QUdpSocket::ShareAddress|QUdpSocket::ReuseAddressHint);
    qDebug() << "bind";
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dealMsg()));

    //用于连接网关TCP
    sockettcp = new QTcpSocket;

    connect(sockettcp,SIGNAL(readyRead()),this,SLOT(data_message()));

    //
    sockettcpftp = new QTcpSocket;

    connect(sockettcpftp,SIGNAL(readyRead()),this,SLOT(data_message()));
}

SetWig::~SetWig()
{
    delete ui;
}

void SetWig::dealMsg()
{
    QHostAddress ip;
    quint16 port;
    QByteArray buf;
    buf.resize(udpSocket->pendingDatagramSize());  //调整buf的缓冲区的大小.设置为等于udpSocket所接收的数据报的大小。
    qDebug() << "wait";
    udpSocket->readDatagram(buf.data(),buf.size(),&ip,&port);//接收对端端口号IP地址
    qDebug() << ip<<port;
    if ((qstrcmp(buf.data(),"yes")) == 0) {
        qDebug() << " my company device";
        QString str = QString("%1:%2").arg(ip.toString()).arg(port);
        qDebug() << "Address: " << str;
        QListWidgetItem *item = new QListWidgetItem;
        item->setText(str);
        ui->listWidget_list->addItem(item);
        ui->listWidget_message->addItem("收到设备响应，等待连接");
    }
}

void SetWig::on_pushButton_search_clicked()
{
    QString ip = ui->lineEdit_input->text();
    int port = 1024;
    QString msg = "coffee";
    qDebug() << "coffee";
    udpSocket->writeDatagram(msg.toUtf8(),QHostAddress(ip),port);//UDP广播发送自定义校验码
    ui->listWidget_message ->addItem("正在搜索设计中。。。");
    qDebug() << "send";
}

void SetWig::on_success_connect_tcp()
{
    QJsonObject ONE;
    ONE.insert("type",1);
    QJsonDocument document;
    document.setObject(ONE);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString strJson(byteArray);
    sockettcp->write(strJson.toLocal8Bit().data(),strJson.toLocal8Bit().length());
}

void SetWig::on_pushButton_heartbeat_clicked()
{
    QJsonObject three;
    three.insert("type",3);
    QJsonDocument document;
    document.setObject(three);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString strJson(byteArray);
    sockettcp->write(strJson.toLocal8Bit().data(),strJson.toLocal8Bit().length());
}

void SetWig::data_message()
{
    QString flag;
    QString msg;
    int upConfig=0;
    int type=0;
    int result=0;
    msg.clear();
    //msg=QString::fromLocal8Bit(sockettcp->readAll());
    msg=QString::fromLocal8Bit(sockettcp->readAll());

    qDebug() << "msg:"<<msg;
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
        qDebug() << "Json格式错误！" << jsonError.error;
        return;
    }//封包数据正确性判断

    qDebug() << "连接网关TCP服务器,网关回复";
    if (doc.isObject())
    {
        qDebug() << "解析json";
        QJsonObject jsonObject = doc.object();
        // 获取up_config值
        if (jsonObject.contains("up_config")) {
            QJsonValue upConfigValue = jsonObject["up_config"];
            upConfig = upConfigValue.toInt();
        }
        qDebug() << "up_config:"<<upConfig;
        // 获取type值

        if (jsonObject.contains("type")) {
            QJsonValue typeValue = jsonObject["type"];
            type = typeValue.toInt();
        }
        qDebug() << "type:"<<type;
        // 获取result值
        if (jsonObject.contains("result")) {
            QJsonValue resultValue = jsonObject["result"];
            result = resultValue.toInt();
        }
        qDebug() << "result:"<<result;
        qDebug() << "upConfig:"<<upConfig;
        if(upConfig==1)//QT给网关下发点表
        {
            qDebug() << "QT给网关下发点表"<<upConfig;
            QJsonObject typeone,dataone;
            typeone.insert("type",2);//type==2点表传输标志位（配置下发协议）
            dataone.insert("flag","start");//发送：网关准备接收
            dataone.insert("file_name","node.json");
            dataone.insert("file_len",560);
            typeone.insert("data",QJsonValue(dataone));
            QJsonDocument data;
            data.setObject(typeone);//建立json对象
            QByteArray byte_data=data.toJson(QJsonDocument::Compact);
            QString reply(byte_data);
            qDebug() << "reply:"<<reply;
            sockettcp->write(reply.toLocal8Bit().data(),reply.toLocal8Bit().length());//发送

        }
        if(upConfig==0)//QT不需给网关下发点表，网关上传QT配置信息
        {
            //解析网关配置信息
            QString mqttaddr;
            int mqttport=0;
            QString videoaddr;
            int videoport=0;
            if (jsonObject.contains("data")) {
                QJsonValue dataValue = jsonObject["data"];
                if (dataValue.isObject()) {
                    QJsonObject dataObject = dataValue.toObject();
                    if (dataObject.contains("mqtt_config")) {
                        QJsonValue mqttValue = dataObject["mqtt_config"];
                        QJsonObject mqttobject=mqttValue.toObject();

                        QJsonValue mqtt_addr=mqttobject["mqtt_addr"];
                        mqttaddr=mqtt_addr.toString();
                        qDebug() << "mqtt_addr:" <<mqttaddr;
                        mqttobject["mqtt_addr"]=mqttaddr;

                        QJsonValue mqtt_port=mqttobject["mqtt_port"];
                        mqttport=mqtt_port.toInt();
                        qDebug() << "mqttport:" <<mqttport;
                        mqttobject["qtt_port"]=mqttport;

                    }
                    if (dataObject.contains("video_config")) {
                        QJsonValue videoValue = dataObject["video_config"];
                        QJsonObject videoobject=videoValue.toObject();

                        QJsonValue video_addr=videoobject["video_addr"];
                        videoaddr=video_addr.toString();
                        qDebug() << "video_addr:" <<videoaddr;
                        videoobject["video_addr"]=videoaddr;

                        QJsonValue video_port=videoobject["video_port"];
                        videoport=video_port.toInt();
                        qDebug() << "videoport:" <<videoport;
                        videoobject["video_port"]=videoport;

                    }
                }
            }
        }
        if(jsonObject.contains("data"))
        {
            //检查“data"获取flag
            QJsonValue dataValue = jsonObject.value("data");
            if(dataValue.isObject())
            {
                QJsonObject dataObject = dataValue.toObject();
                if(dataObject.contains("flag"))
                {
                    QJsonValue flagValue = dataObject.value("flag");
                    if(flagValue.isString())
                        flag = flagValue.toString();
                    qDebug() << "flag:" << flag;
                }
            }
        }
        if(flag=="start")
        {
            qDebug() << "等待连接" ;
            QString contenttcp;
            sockettcpftp->connectToHost(QHostAddress(tcpip),1025);
            ui->listWidget_message->addItem("点表文件传输端口已连接~~~~");
            QFile file(":/new/prefix1/node.json");
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                // 读取文件内容
                contenttcp = file.readAll();

                file.close();
            }
            //contenttcp = "tcptcptcptcptcpc测试";
            qDebug() << "读出点表内容："<<contenttcp ;
            sockettcpftp->write(contenttcp.toLocal8Bit().data(),contenttcp.toLocal8Bit().length());//新的1025端口建立发送

            //sockettcpftp->disconnectFromHost();//新的1025端口发送完毕之后断开

            QJsonObject typetwo,datatwo;
            typetwo.insert("type",2);//type==2点表传输标志位（配置下发协议）
            datatwo.insert("flag","stop");//发送：网关准备接收

            typetwo.insert("data",QJsonValue(datatwo));
            QJsonDocument datamsg;
            datamsg.setObject(typetwo);//建立json对象
            QByteArray byte_data=datamsg.toJson(QJsonDocument::Compact);
            QString replystop(byte_data);
            qDebug() << "reply:"<<replystop;
            sockettcp->write(replystop.toLocal8Bit().data(),replystop.toLocal8Bit().length());//发送
            ui->listWidget_message->addItem("点表文件传输完毕~~~~");
        }
        if(type == 2)
        {
            if(flag=="stop")
            {
                //sockettcpftp->disconnect();
                ui->listWidget_message->addItem("传输端口已断开");
            }
        }
        if(type == 3){
            ui->listWidget_message->addItem("连接正常~~~~~");
        }
    }
}

void SetWig::on_pushButton_disconnect_clicked()
{
    sockettcp->disconnectFromHost();
    ui->listWidget_message->addItem("控制端口已断开~~~");
}

void SetWig::on_listWidget_list_itemClicked(QListWidgetItem *item)
{
    tcpip = item->text().split(":")[0];
    int tcpprot = item->text().split(":")[1].toInt();
    //获取到IP和端口后，连接网关TCP服务器
    sockettcp->connectToHost(tcpip,tcpprot);
    connect(sockettcp,SIGNAL(connected()),this,SLOT(on_success_connect_tcp()));
    ui->listWidget_message ->addItem("连接网关TCP服务器");
    qDebug() << "连接网关TCP服务器";
}

void SetWig::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPixmap pix(":/new/prefix2/picture_tubiao/beijing2.png");
    painter.drawPixmap(0, 0, pix);

    QGraphicsOpacityEffect * opacity1 = new QGraphicsOpacityEffect(this);
    QGraphicsOpacityEffect * opacity2 = new QGraphicsOpacityEffect(this);



    opacity1->setOpacity(0.6); //透明范围同窗口透明度
    opacity2->setOpacity(0.6); //透明范围同窗口透明度


    ui->listWidget_list->setStyleSheet("border-radius:10px");
    ui->listWidget_list->setGraphicsEffect(opacity1);
    ui->listWidget_message->setStyleSheet("border-radius:10px");
    ui->listWidget_message->setGraphicsEffect(opacity2);


}
